package com.java.cg.goods.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.cg.goods.dao.SkuDao;
import com.java.cg.goods.entity.Sku;
import com.java.cg.goods.service.SkuService;
import com.java.common.utils.PageUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service("skuService")
public class SkuServiceImpl extends ServiceImpl<SkuDao, Sku> implements SkuService {

	@Override
	public PageUtils<Sku> queryPage(Integer page, Integer size, Sku sku) {
		IPage<Sku> skuPage = this.page(
				new Page<>(page, size),
				new LambdaQueryWrapper<Sku>().eq(StrUtil.isNotEmpty(sku.getStatus()), Sku::getStatus, sku.getStatus())
		);

		return new PageUtils<>(skuPage);
	}

	/**
	 * 扣减库存
	 */
	@Override
	public void decrCount(Map<String, Integer> decrMap) {
		for (Map.Entry<String, Integer> entry : decrMap.entrySet()) {
			//商品id
			Long skuId = Long.valueOf(entry.getKey());
			//递减数量
			Object value = entry.getValue();
			Integer num = Integer.valueOf(value.toString());

			//库存 >= 递减数量
			Sku sku = this.baseMapper.selectById(skuId);
			if (sku.getNum() >= num) {
				this.baseMapper.decrCount(skuId, num);
			}

		}
	}

}